<template>
  <el-dialog
    v-model="visible"
    title="新增会员"
    @close="handleClose"
  >
    <el-form :model="newMember" label-width="120px">
      <!-- 其他表单项 -->
      <el-form-item label="名字">
        <el-input v-model="newMember.name"></el-input>
      </el-form-item>
      <el-form-item label="首次充值金额">
        <el-input v-model="newMember.rechargeAmount" type="number"></el-input>
      </el-form-item>
      <el-form-item label="会员等级">
        <el-select v-model="newMember.lv" placeholder="请选择会员等级">
          <el-option
            v-for="level in vipLevels"
            :key="level.id"
            :label="level.name"
            :value="level.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人">
        <el-select v-model="newMember.responsible" placeholder="请选择负责人">
          <el-option
            v-for="responsible in vipLevels2"
            :key="responsible.id"
            :label="responsible.name"
            :value="responsible.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 合并省市区选择为一列 -->
      <el-form-item label="地区">
        <div style="display: flex; gap: 10px;">
          <el-select style="width:120px" v-model="newMember.province" placeholder="请选择省份" @change="onProvinceChange">
            <el-option
              v-for="area in currentProvinces"
              :key="area.value"
              :label="area.label"
              :value="area.value"
            ></el-option>
          </el-select>
          <el-select style="width:120px" v-model="newMember.city" placeholder="请选择城市" @change="onCityChange" :disabled="!newMember.province">
            <el-option
              v-for="area in currentCities"
              :key="area.value"
              :label="area.label"
              :value="area.value"
            ></el-option>
          </el-select>
          <el-select style="width:120px" v-model="newMember.district" placeholder="请选择区县" :disabled="!newMember.city">
            <el-option
              v-for="area in currentDistricts"
              :key="area.value"
              :label="area.label"
              :value="area.value"
            ></el-option>
          </el-select>
        </div>
      </el-form-item>
      <!-- 新增电话号码输入项 -->
      <el-form-item label="电话号码">
        <el-input
          v-model="newMember.phone"
          :maxlength="11"
          @input="filterPhoneNumber"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleAddMember">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, onMounted } from 'vue';
import { Get_Level } from '@/api/customerVip/index';
import { Get_user } from '@/api/customer/index';

// 引入省市区数据
let addressData = {};
const fetchAddressData = async () => {
  try {
    const response = await import('./cities.json');
    addressData = response.default;
    // 初始化省份数据
    currentProvinces.value = Object.keys(addressData).map(province => ({
      value: province,
      label: province
    }));
  } catch (error) {
    console.error('获取地址数据失败', error);
  }
};

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:modelValue', 'addMember']);

const visible = ref(props.modelValue);
const newMember = ref({
  name: '',
  rechargeAmount: 0,
  lv: '',
  responsible: '',
  province: '',
  city: '',
  district: '',
  address: '',
  // 新增电话号码字段
  phone: ''
});

const vipLevels = ref([]);
const vipLevels2 = ref([]);
// 当前显示的省份列表
const currentProvinces = ref([]);
// 当前显示的城市列表
const currentCities = ref([]);
// 当前显示的区县列表
const currentDistricts = ref([]);

const fetchVipLevels = async () => {
  const res = await Get_Level();
  if (res.code === 0) {
    vipLevels.value = res.data.data;
  }
};
const fetchVipLevels2 = async () => {
  const res = await Get_user({
    keys: []
  });
  if (res.code === 0) {
    vipLevels2.value = res.data.data;
  }
};

onMounted(async () => {
  await fetchAddressData();
  await fetchVipLevels();
  await fetchVipLevels2();
  visible.value = props.modelValue;
});

const handleClose = () => {
  emits('update:modelValue', false);
};

const handleAddMember = () => {
  // 验证必填字段
  const { name, rechargeAmount, lv, responsible, province, city, district, phone } = newMember.value;
  if (!name || !rechargeAmount || !lv || !responsible || !province || !city || !district || !phone) {
    alert('请确保所有必填字段都已填写！');
    return;
  }

  // 合并省市区为字符串
  const fullAddress = `${newMember.value.province}${newMember.value.city}${newMember.value.district}`;
  // 可以将合并后的地址添加到 newMember 对象中
  newMember.value.address = fullAddress;
  emits('addMember', newMember.value);
  emits('update:modelValue', false);
};

const onProvinceChange = (provinceValue: string) => {
  const selectedProvinceData = addressData[provinceValue];
  if (selectedProvinceData) {
    const cityList = Object.keys(selectedProvinceData);
    currentCities.value = cityList.map(city => ({
      value: city,
      label: city
    }));
    newMember.value.city = '';
    newMember.value.district = '';
    currentDistricts.value = [];
  }
};

const onCityChange = (cityValue: string) => {
  const selectedProvinceData = addressData[newMember.value.province];
  if (selectedProvinceData) {
    const districtList = selectedProvinceData[cityValue] || [];
    currentDistricts.value = districtList.map(district => ({
      value: district,
      label: district
    }));
    newMember.value.district = '';
  }
};

// 过滤非数字字符
const filterPhoneNumber = (value: string) => {
  newMember.value.phone = value.replace(/\D/g, '');
};
</script>

<style scoped>
/* 可以在这里添加对话框样式 */
</style>
